﻿using Digitalmes.Domain.Enums;
using Digitalmes.Scada.Management;
using Digitalmes.Scada.Models;

namespace Digitalmes.Scada.Handlers;

/// <summary>
/// 设备心跳信息处理。
/// </summary>
internal sealed class HeartbeatApiHandler : IDeviceHeartbeatApi
{
    private readonly EquipmentStateManager _equipmentStateManager;
    private readonly ILogger _logger;

    public HeartbeatApiHandler(EquipmentStateManager equipmentStateManager,
        ILogger<HeartbeatApiHandler> logger)
    {
        _equipmentStateManager = equipmentStateManager;
        _logger = logger;
    }

    public async Task ChangeAsync(string channelName, Device device, Tag tag, bool isOnline, CancellationToken cancellationToken)
    {
        EquipmentCodeInput input = new()
        {
            Line = channelName,
            EquipmentCodes = [],
        };

        var tagGroup = device.GetTagGroup(tag.TagId);
        if (tagGroup is null)
        {
            // 心跳是跟随设备设定的
            input.EquipmentCodes.AddRange(device.TagGroups.Select(s => s.Name));
        }
        else
        {
            // 心跳对应具体的分组
            input.EquipmentCodes.Add(tagGroup.Name);
        }

        try
        {
            // 更改设备运行状态（Running/Offline）
            var runningState = isOnline ? EquipRunningState.Running : EquipRunningState.Offline;
            await _equipmentStateManager.ChangeStateAsync(input, runningState, cancellationToken);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "[{ApiHandler}] 心跳数据预处理异常。", nameof(HeartbeatApiHandler));
        }
    }
}
